from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from app import crud, schemas
from app.database import get_db
from app.api.auth import get_current_user
from app.schemas.user import UserInDB
from app.schemas.attachment import AttachmentCreate, AttachmentResponse
import os
import uuid
from typing import List

router = APIRouter()

# 配置上传目录
UPLOAD_DIR = "uploads"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)

# 上传附件
@router.post("/upload", response_model=AttachmentResponse, status_code=status.HTTP_201_CREATED)
async def upload_attachment(
    entity_type: str = Form(...),
    entity_id: int = Form(...),
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    # 生成唯一文件名
    file_extension = os.path.splitext(file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"
    file_path = os.path.join(UPLOAD_DIR, unique_filename)
    
    # 保存文件
    try:
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # 创建附件记录
        attachment_data = AttachmentCreate(
            filename=unique_filename,
            original_filename=file.filename,
            file_path=file_path,
            file_size=len(content),
            mime_type=file.content_type,
            entity_type=entity_type,
            entity_id=entity_id
        )
        
        attachment = crud.attachment.create_attachment(
            db=db, 
            attachment=attachment_data, 
            uploaded_by=current_user.id
        )
        
        return attachment
        
    except Exception as e:
        # 如果创建记录失败，删除已上传的文件
        if os.path.exists(file_path):
            os.remove(file_path)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"上传失败: {str(e)}"
        )

# 下载附件 - 这个路由必须放在 /{entity_type}/{entity_id} 之前
@router.get("/download/{attachment_id}")
def download_attachment(
    attachment_id: int,
    db: Session = Depends(get_db)
):
    attachment = crud.attachment.get_attachment(db, attachment_id=attachment_id)
    if not attachment:
        raise HTTPException(status_code=404, detail="附件不存在")
    
    if not os.path.exists(attachment.file_path):
        raise HTTPException(status_code=404, detail="文件不存在")
    
    return FileResponse(
        path=attachment.file_path,
        filename=attachment.original_filename,
        media_type=attachment.mime_type
    )

# 获取实体的附件列表
@router.get("/{entity_type}/{entity_id}", response_model=List[AttachmentResponse])
def get_entity_attachments(
    entity_type: str,
    entity_id: int,
    db: Session = Depends(get_db)
):
    attachments = crud.attachment.get_attachments_by_entity(
        db, entity_type=entity_type, entity_id=entity_id
    )
    return attachments

# 删除附件
@router.delete("/{attachment_id}", response_model=AttachmentResponse)
def delete_attachment(
    attachment_id: int,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    attachment = crud.attachment.delete_attachment(db, attachment_id=attachment_id)
    if not attachment:
        raise HTTPException(status_code=404, detail="附件不存在")
    return attachment